package com.cn.wanxi.service.impl;

import com.cn.wanxi.dao.NavDao;
import com.cn.wanxi.dao.impl.NavImpl;
import com.cn.wanxi.model.NavModel;
import com.cn.wanxi.service.NavService;
import redis.clients.jedis.Jedis;

import java.util.ArrayList;
import java.util.List;

public class NavServiceImpl implements NavService {
    private NavDao navDao = new NavImpl();

    @Override
    public List<NavModel> getNavModelList() {

        List<NavModel> list = new ArrayList<>();
        Jedis jedis = new Jedis();
        jedis.select(10);
        Boolean isHave = jedis.exists("titles");
        if (isHave) {

            List<String> titles = jedis.lrange("titles", 0, jedis.llen("titles"));
//            -1就可以表示所有
            List<String> hrefs = jedis.lrange("hrefs", 0, -1);
            for (int i = 0; i < titles.size(); i++) {
                NavModel navModel = new NavModel();
                navModel.setTitle(titles.get(i));
                navModel.setHref(hrefs.get(i));
                list.add(navModel);
            }
            System.out.println("redis-list");
        } else {
//            得到数据库里面的值
            list = navDao.getNavModelList();
//            将值直接存放到redis
            for (int i = 0; i < list.size(); i++) {
                jedis.rpush("titles", list.get(i).getTitle());
                jedis.rpush("hrefs", list.get(i).getHref());
            }
            System.out.println("mysql-list");

        }

        return list;
    }
}
